package co.yixiang.retail.biz.order.service.impl;

import co.yixiang.common.core.api.YshopException;
import co.yixiang.common.mproot.common.service.impl.BaseServiceImpl;


import co.yixiang.common.mproot.common.utils.QueryHelpPlus;
import co.yixiang.common.mproot.domain.PageResult;
import co.yixiang.common.mproot.dozer.service.IGenerator;


import co.yixiang.retail.biz.order.mapper.YxStoreOrderMapper;
import co.yixiang.retail.biz.order.service.YxStoreOrderService;

import co.yixiang.retail.biz.order.service.YxUserService;
import co.yixiang.retail.biz.product.mapper.*;

import co.yixiang.retail.biz.product.service.StoreProductAttrValueService;

import co.yixiang.retail.biz.user.mapper.YxSystemStoreMapper;
import co.yixiang.retail.biz.user.sevice.YxSystemStoreService;
import co.yixiang.retail.common.annotation.ServiceLock;
import co.yixiang.retail.common.domain.*;

import co.yixiang.retail.common.dto.*;

import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxStoreOrderServiceImpl extends BaseServiceImpl<YxStoreOrderMapper, YxStoreOrder> implements YxStoreOrderService {


    private final IGenerator generator;
    private final YxStoreOrderMapper yxStoreOrderMapper;
    private final YxStoreProductMapper yxStoreProductMapper;
    private final YxSystemStoreService yxSystemStoreService;
    private final StoreProductAttrValueService yxStoreProductAttrValueService;
    private final StoreProductStockValueMapper yxStoreProductStockValueMapper;
    private final YxSystemStoreMapper yxSystemStoreMapper;
    private final YxUserMapper yxUserMapper;
    private final YxStoreTypeMapper yxStoreTypeMapper;
    private final YxBalanceChangeMapper yxBalanceChangeMapper;

    @Override
    public void add(List<YxStoreProduct> products) {
        yxStoreProductMapper.add(products);
    }


    //添加门店进货 余额变化
    @Override
    public void updateRetailMoney(BigDecimal payPrice, Long uid, BigDecimal oldPrice) {
        yxSystemStoreService.updateMoney(payPrice, uid, oldPrice);
    }

    @Override
    public BigDecimal queryNowMoney(Long uid) {
        return yxStoreProductMapper.queryMoney(uid);
    }

    @Override
    @ServiceLock
    public void sumitOrder(YxStoreOrder yxStoreOrder) {
        Date now = new Date();
        Long uid = yxStoreOrder.getUid();
        if (null == uid) {
            throw new YshopException("未指定购买者,请重试");
        }
        Integer storeId = yxStoreOrder.getStoreId();
        if (null == storeId) {
            throw new YshopException("门店不存在");
        }
        String userPhone = yxStoreOrder.getUserPhone();
        RyzUseIntegralDetailDto ryzUseIntegralDetailDto = new RyzUseIntegralDetailDto();
        Random random = new Random();
        int rannum = (int) (random.nextDouble() * (9999 - 1000 + 1)) + 1000;
        String number = String.format("%05d", rannum);
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmSS");
        String dateStr = df.format(now);
        String orderId = "RYZ" + dateStr + number;

        yxStoreOrder.setCost(new BigDecimal(0.00));
        yxStoreOrder.setUnique(orderId);
        yxStoreOrder.setOrderId(orderId);
        yxStoreOrder.setPayTime(now);
        /**积分详情**/
        ryzUseIntegralDetailDto.setSaleCode(yxStoreOrder.getSaleCode());
        ryzUseIntegralDetailDto.setOrderId(orderId);
        ryzUseIntegralDetailDto.setUserId(uid);
        ryzUseIntegralDetailDto.setPhone(userPhone);
        ryzUseIntegralDetailDto.setStoreId(storeId);

        /* 支付方式（1：积分支付2：余额支付）*/
        String payType = yxStoreOrder.getPayType();
        BigDecimal payPrice = yxStoreOrder.getPayPrice();
        Integer buyStoreId = yxStoreOrder.getBuyStoreId();
        List<YxStoreProduct> product = null;
        //TODO day0501
        BigDecimal money = yxStoreProductMapper.queryMoney(uid);
        if (null==money){
            throw new YshopException("未知异常,请联系管理员");
        }
        YxSystemStore yxSystemStores = null;
        if (storeId == -1) {
            yxStoreOrder.setSellerRetailname("平台");
            yxStoreOrder.setSellerPhone("110");
            if (money.compareTo(yxStoreOrder.getPayPrice()) < 0) {
                throw new YshopException("门店余额不足");
            } else {
                //修改门店余额
                this.updateRetailMoney(payPrice, uid, money);
                yxStoreOrder.setPaid(1);
            }
            //库存
            product = yxStoreOrder.getProducts();
            for (YxStoreProduct a : product) {
                Long id = a.getId();
                Integer amount = a.getNum();
                YxStoreProductAttrValue yxStoreProduct = yxStoreProductAttrValueService.getById(id);
                Integer stock = yxStoreProduct.getStock();
                if (stock < amount) {
                    throw new YshopException("库存不足");
                }
                this.updateCenterStock(id,amount);
            }
        } else {
            yxSystemStores = yxStoreProductMapper.queryRetail(storeId);
            if (null == yxSystemStores) {
                throw new YshopException("卖家门店不存在");
            }
            //查询门店余额
            yxStoreOrder.setSellerPhone(yxSystemStores.getPhone());
            yxStoreOrder.setSellerRetailname(yxSystemStores.getName());
            if (money.compareTo(payPrice) < 0) {
                throw new YshopException("门店余额不足");
            } else {
                //修改门店余额
                if ("1".equals(payType)) {
                    //积分支付--、门店服务费++
                    yxSystemStoreService.updateSalesCode(uid, storeId, payPrice, ryzUseIntegralDetailDto);
                    yxStoreOrder.setPaid(1);
                } else {
                    this.updateRetailMoney(payPrice, uid, money);
                    yxStoreOrder.setPaid(1);
                }
            }
            //库存
            product = yxStoreOrder.getProducts();
            for (YxStoreProduct a : product) {
                //商品规格id
                Long id = a.getId();
                Integer amount = a.getNum();
                StoreProductStockValue yxStoreProduct = yxStoreProductStockValueMapper.query(id, storeId);
                Integer stock = yxStoreProduct.getStock();
                if (stock < amount) {
                    throw new YshopException("库存不足请重新挑选");
                }
                this.updateRetailStock(id, amount, storeId);
            }
        }
        //添加订单
        this.save(yxStoreOrder);
            if (storeId == -1) {

                List<YxStoreProduct> products = yxStoreOrder.getProducts();
                String orderIds = yxStoreOrder.getOrderId();
                Long oid = yxStoreOrder.getId();
                String sellerPhone = yxStoreOrder.getSellerPhone();
                String sellerRetailname = yxStoreOrder.getSellerRetailname();

                products.forEach((e) -> e.setOid(oid));
                products.forEach((e) -> e.setOrderId(orderIds));
                products.forEach((e) -> e.setPhone(sellerPhone));
                products.forEach((e) -> e.setName(sellerRetailname));
                products.forEach((e) -> e.setStoreId(storeId));
                products.forEach((e) -> e.setBuyStoreId(buyStoreId));
                this.add(products);
                //进货日志
                this.addLog(products);
            } else {

                product = yxStoreOrder.getProducts();
                String phone = yxSystemStores.getPhone();
                String name = yxSystemStores.getName();
                Long oid = yxStoreOrder.getId();
                String orderIds = yxStoreOrder.getOrderId();
                String realName = yxStoreOrder.getRealName();
                for (YxStoreProduct yxStoreProduct : product) {
                    yxStoreProduct.setOid(oid);
                    yxStoreProduct.setPhone(phone);
                    yxStoreProduct.setName(name);
                    yxStoreProduct.setRealName(realName);
                    yxStoreProduct.setOrderId(orderIds);
                    yxStoreProduct.setStoreId(storeId);
                    yxStoreProduct.setBuyStoreId(buyStoreId);
                }
                if ("1".equals(payType)) {
                    //销货日志
                    this.addSalesLog(product);
                } else {
                    //进货日志
                    this.addLog(product);
                }
                this.add(product);
            }
    }

    @Override
    public void addLog(List<YxStoreProduct> products) {
        yxStoreProductMapper.addLog(products);
    }

    @Override
    public void addSalesLog(List<YxStoreProduct> products) {
        yxStoreProductMapper.addSalesLog(products);
    }

    @Override
    public void updateRetailStock(Long id, Integer amount, Integer storeId) {
        yxStoreProductMapper.updateRetailStock(id, amount, storeId);
    }

    @Override
    public void updateCenterStock(Long id, Integer amount) {
        yxStoreProductMapper.updateCenterStock(id, amount);
    }

    @Override
    public PageResult<YxStoreOrderDto> queryAll(YxStoreOrderSalesQueryCriteria criteria, Pageable pageable) {
        Integer orderStatus = criteria.getOrderStatus();
        switch (orderStatus){
            case 0:
                criteria.setStatus(0);
                break;
            case 1:
                criteria.setStatus(1);
                break;
            case 2:
                criteria.setStatus(2);
                break;
            case 3:
                criteria.setStatus(3);
                break;
            case 4:
                criteria.setStatus(4);
                break;
            case 5:
                criteria.setStatus(5);
        }

        getPage(pageable);
        PageInfo<YxStoreOrder> page = new PageInfo<>(queryAll(criteria));
        return generator.convertPageInfo(page, YxStoreOrderDto.class);
    }

    @Override
    public List<YxStoreOrder> queryAll(YxStoreOrderSalesQueryCriteria criteria) {
        List<YxStoreOrder> list1 = new ArrayList<>();
        List<YxStoreOrder> list = baseMapper.selectList(QueryHelpPlus.getPredicate(YxStoreOrder.class, criteria));
        list.forEach((e)->{

            Long uid = e.getUid();
            String s = yxStoreOrderMapper.queryNick(uid);
            e.setNickName(s);

            list1.add(e);
        });

        return list1;
    }


    @Override
    public List<YsStoreOrderSalesDetailDto> queryAll(YxStoreOrderSalesDetailQueryCriteria criteria) {
        return yxStoreOrderMapper.queryById(criteria);
    }

    @ServiceLock
    @Override
    public void shipments(YxStoreOrderShipmentsDto cmd) {
        //订单信息
        YxStoreOrder yxStoreOrder = yxStoreOrderMapper.selectById(cmd.getId());
        //买方门店

        Integer storeId = yxSystemStoreMapper.queryByUserId(cmd.getUid());
        //卖方门店类型
        Integer retailType = yxSystemStoreMapper.queryById(cmd.getStoreId());
        List<YsStoreOrderSalesDetailDto> detailDtoList = yxStoreOrderMapper.query(cmd);
        //买方库存++
        buyerAddInventory(detailDtoList,cmd,storeId);
        //卖方
        YxUser yxUser = yxUserMapper.queryByStoreId(cmd.getStoreId());
        //服务费比例
        BigDecimal service = yxStoreTypeMapper.queryByLevel(String.valueOf(retailType));
        //社区店服务费
        BigDecimal community = yxStoreTypeMapper.queryByLevel("1");
        BigDecimal serviceCharge = service.subtract(community);
        //变化金额
        BigDecimal userFront = yxStoreOrder.getPayPrice().add(yxStoreOrder.getPayPrice().multiply(serviceCharge));
        if(userFront.compareTo(BigDecimal.ZERO) < 0){
            throw new YshopException("门店层级与服务费不匹配,请联系管理员");
        }
        //服务费日志记录
        YxBalanceChange yxBalanceChange = new YxBalanceChange();
        yxBalanceChange.changeBaseInfo(yxUser,userFront);
        yxBalanceChangeMapper.insert(yxBalanceChange);
        //卖方服务付费++
        yxUser.setStoreBalance(yxUser.getStoreBalance().add(userFront));
        yxUserMapper.updateById(yxUser);
        //订单状态修改
        yxStoreOrder.setStatus(4);
        yxStoreOrder.setUpdateTime(new Date());
        yxStoreOrderMapper.updateById(yxStoreOrder);
    }

    /**
     * 买方加库存
     * @param detailDtoList
     */
    public void buyerAddInventory(List<YsStoreOrderSalesDetailDto> detailDtoList,YxStoreOrderShipmentsDto cmd,Integer storeId){
        detailDtoList.stream().forEach(ysStoreOrderSalesDetailDto -> {
            YxStoreProductStockValue yxStoreProductStockValueExist =
                    yxStoreProductStockValueMapper.queryBySkuIdAndStoreId(ysStoreOrderSalesDetailDto.getSkuId(), storeId);
            if (yxStoreProductStockValueExist != null){
                //存在就增加进货量
                yxStoreProductStockValueExist.setPurchaseVolume(yxStoreProductStockValueExist.getPurchaseVolume()+ysStoreOrderSalesDetailDto.getAmount().intValue());
                yxStoreProductStockValueExist.setStock(yxStoreProductStockValueExist.getStock()+ysStoreOrderSalesDetailDto.getAmount().intValue());
                yxStoreProductStockValueMapper.updateById(yxStoreProductStockValueExist);
            }else {
                //买方库存++
                YxStoreProductStockValue yxStoreProductStockValue = new YxStoreProductStockValue();
                yxStoreProductStockValue.shipments(ysStoreOrderSalesDetailDto,storeId,cmd.getStoreId());
                yxStoreProductStockValueMapper.insert(yxStoreProductStockValue);
            }
        });
    }

    @ServiceLock
    @Override
    public void refuseBill(YxStoreOrderShipmentsDto cmd) {
        //拒单的订单信息
        YxStoreOrder yxStoreOrder = yxStoreOrderMapper.selectById(cmd.getId());
        //买家信息
        YxUser yxUser = yxUserMapper.queryByUid(cmd.getUid().intValue());
        //买方余额日志记录
        YxBalanceChange yxBalanceChange = new YxBalanceChange();
        yxBalanceChange.refuseBill(yxUser , yxStoreOrder.getPayPrice());
        yxBalanceChangeMapper.insert(yxBalanceChange);
        //买家退款
        yxUser.setStoreBalance(yxUser.getStoreBalance().add(yxStoreOrder.getPayPrice()));
        yxUserMapper.updateById(yxUser);
        //卖家增加库存
        List<YsStoreOrderSalesDetailDto> detailDtoList = yxStoreOrderMapper.query(cmd);
        detailDtoList.stream().forEach(ysStoreOrderSalesDetailDto->{
            YxStoreProductStockValue yxStoreProductStockValue = yxStoreProductStockValueMapper.queryBySkuIdAndStoreId(ysStoreOrderSalesDetailDto.getSkuId(), yxStoreOrder.getStoreId());
            yxStoreProductStockValue.setStock(yxStoreProductStockValue.getStock() + ysStoreOrderSalesDetailDto.getAmount());
            yxStoreProductStockValueMapper.updateById(yxStoreProductStockValue);
        });
        //订单状态改为拒单
        yxStoreOrder.setStatus(5);
        yxStoreOrder.setUpdateTime(new Date());
        yxStoreOrderMapper.updateById(yxStoreOrder);
    }
}
